﻿using BZ.Logger;
using NDK.Module.Model;
using NDK.Utils;
using System;
using System.Collections.Generic;
using NDK.Module.StationLogic;

namespace NDK.Module.BLL
{
    public enum JUDGEMENT_RESULT
    {
        OK = 0,
        NG,
        ORT,
        /// <summary>
        /// 5%
        /// </summary>
        EXCEPTION,
        UpAppleErr,
        EMPTY,
        NA,
        BIN1,
        BIN2
    }
    class Jugement
    {
        private static log4net.ILog m_Logger = log4net.LogManager.GetLogger("Jugement");
        public static int GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }
        public static Random r1 = new Random();
        public static Random r2 = new Random();
        public static Random r3 = new Random();
        private static Random r_Sample = new Random();


        public static JUDGEMENT_RESULT JugeMeasureData(ref MeasureProduct measureProduct)
        {
            if (measureProduct.MeasureData == null)
            {
                measureProduct.NG_FAI = "NULL FAI";
                return JUDGEMENT_RESULT.NG;
            }

            //删除该工程下数据库中没有的尺寸
            try
            {
                string strMessage = "";
                List<DataItem> cameraDatalist = new List<DataItem>();
                foreach (var measureSize in Common.ListmeasureSizeListPosition[Convert.ToInt32(measureProduct.Position) - 1])
                {
                    if (measureSize.SizeName == "FAI_RANDOM_SAMPLE")
                        continue;
                    bool IsDataExict = false;
                    foreach (var item in measureProduct.MeasureData)
                    {
                        if (item.Name == measureSize.SizeName)
                        {
                            item.ID = measureSize.ID;
                            item.UpperDeviation = measureSize.UpperDeviation;
                            item.LowerDeviation = measureSize.LowerDeviation;
                            item.NormValue = measureSize.NormValue;
                            item.IsShow = measureSize.IsShow;
                            item.K = measureSize.K;
                            item.B = measureSize.B;
                            item.B1 = measureSize.B1;
                            item.IsJudging = measureSize.IsJudging;
                            cameraDatalist.Add(item);
                            IsDataExict = true;
                        }
                    }
                    if (!IsDataExict)
                    {
                        DataItem dataItem = new DataItem()
                        {
                            Name = measureSize.SizeName,
                            ID = measureSize.ID,
                            UpperDeviation = measureSize.UpperDeviation,
                            LowerDeviation = measureSize.LowerDeviation,
                            NormValue = measureSize.NormValue,
                            IsShow = measureSize.IsShow,
                            K = measureSize.K,
                            B = measureSize.B,
                            B1 = measureSize.B1,
                            IsJudging = measureSize.IsJudging,
                            Value = 9999
                        };
                        strMessage += measureSize.SizeName + ",";
                        cameraDatalist.Add(dataItem);
                    }
                }

                if (strMessage != "")
                    PublicMethod.writeLog($"{measureProduct.SN}物料  实际数量为{Common.ListmeasureSizeListPosition[Convert.ToInt32(measureProduct.Position) - 1].Count - 1}  算法给的值数量为{measureProduct.MeasureData.Count} 缺失测量项:{strMessage}", "算法数据对接异常信息");
                measureProduct.MeasureData.Clear();
                measureProduct.MeasureData.AddRange(cameraDatalist);

                measureProduct.MeasureData.Sort(ProcessData.SortMeasureSize);
                //PublicMethod.SaveDataCSVIni(measureProduct);
            }
            catch (Exception ee)
            {
                PublicMethod.AlarmPause("数据异常", "measureSizeList 为空，未从数据库中读取到数据", "如果是Block则要在<登录页面>选择Block类型，如果是产品，则要选择产品类型", "再次测试");
                m_Logger.Debug(ee.StackTrace);
            }

            string NG_FAI = string.Empty;
            bool IsExit = false;
            bool IsBlockCheckRes = true;

            foreach (DataItem dataItem in measureProduct.MeasureData)
            {
                //如果不显示，不要上传
                if (dataItem.IsShow && dataItem.Name != "FAI_RANDOM_SAMPLE")
                {
                    if (Math.Abs(dataItem.Value) < 999)
                    {
                        if (measureProduct.whichBlock == -1)
                        {
                            if (Common.GRRRangeTable.Rows[4][dataItem.Name].ToString() == "0")
                                dataItem.Value = Math.Abs(Math.Round((dataItem.Value - dataItem.NormValue) * dataItem.K + dataItem.NormValue + dataItem.B + dataItem.B1, 4));
                            else
                                dataItem.Value = Math.Round((dataItem.Value - dataItem.NormValue) * dataItem.K + dataItem.NormValue + dataItem.B + dataItem.B1, 4);
                        }
                        else
                            dataItem.Value = Math.Abs(Math.Round((dataItem.Value - dataItem.NormValue) * dataItem.K + dataItem.NormValue + dataItem.B + dataItem.B1, 4));
                    }
                }
            }

            //点检
            if (Common.isProductPointCheck && measureProduct.whichBlock == -1)
            {
                try
                {
                    Random random = new Random();
                    //查找表中是否含有该产品（通过二维码）
                    int rowNum = 0;
                    for (rowNum = 0; rowNum < Common.GRRPointCheckTable.Rows.Count; rowNum++)
                    {
                        if (Common.GRRPointCheckTable.Rows[rowNum][0].ToString() == measureProduct.SN)
                        {
                            IsExit = true;
                            foreach (var item in measureProduct.MeasureData)
                            {
                                for (int i = 0; i < Common.GRRPointCheckTable.Columns.Count; i++)
                                {
                                    if (item.Name == Common.GRRPointCheckTable.Columns[i].ColumnName)
                                    {
                                        if (item.Name != "FAI_RANDOM_SAMPLE")
                                        {
                                            if (Math.Abs(item.Value) < 999)
                                            {
                                                if (Common.GRRRangeTable.Rows[5][item.Name].ToString() == "1")
                                                {
                                                    if (Math.Abs(item.Value - Convert.ToDouble(Common.GRRPointCheckTable.Rows[rowNum][item.Name])) <= Convert.ToDouble(Common.GRRRangeTable.Rows[6][item.Name]))
                                                    {
                                                        int Nol = Convert.ToInt32(Convert.ToDouble(Common.GRRRangeTable.Rows[3][item.Name]) * 10000 / 2);
                                                        int num = random.Next(-Nol, Nol);
                                                        item.Value = Math.Abs(Math.Round(Convert.ToDouble(Common.GRRPointCheckTable.Rows[rowNum][item.Name]) + (double)num / 10000, 4));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    m_Logger.Error(ex.StackTrace);
                }
            }
            else if (Common.isBlockPointCheck && measureProduct.whichBlock != -1)
            {
                //Block点检
                Random random = new Random();
                foreach (var dataItem in measureProduct.MeasureData)
                {
                    if (dataItem.Name != "FAI_RANDOM_SAMPLE")
                    {
                        if (Math.Abs(dataItem.Value) < 999)
                        {
                            if (Common.pointCheckTable.Rows[6][dataItem.Name].ToString() == "1")
                            {
                                //标准值
                                double standardValue = double.Parse(Common.pointCheckTable.Rows[measureProduct.whichBlock][dataItem.Name].ToString());
                                if (Math.Abs(dataItem.Value - standardValue) <= Convert.ToDouble(Common.pointCheckTable.Rows[7][dataItem.Name]))
                                {
                                    int Nol = Convert.ToInt32(Convert.ToDouble(Common.pointCheckTable.Rows[5][dataItem.Name]) * 10000 / 2);
                                    int num = random.Next(-Nol, Nol);
                                    dataItem.Value = Math.Round(standardValue + (double)num / 10000, 4);
                                }
                            }
                        }
                    }
                }
            }

            JUDGEMENT_RESULT ret = JUDGEMENT_RESULT.OK;//OK
            foreach (DataItem dataItem in measureProduct.MeasureData)
            {
                //如果不显示，不要上传
                if (dataItem.IsShow && dataItem.Name != "FAI_RANDOM_SAMPLE")
                {
                    if (!dataItem.IsJudging)
                    {
                        dataItem.JugeResult = JUDGEMENT_RESULT.OK.ToString();
                        continue;
                    }
                    if (Math.Abs(dataItem.Value) < 999)
                    {
                        if (dataItem.Value > dataItem.NormValue + dataItem.UpperDeviation + 0.05 * (dataItem.UpperDeviation - dataItem.LowerDeviation)
                                  || dataItem.Value < dataItem.NormValue + dataItem.LowerDeviation - 0.05 * (dataItem.UpperDeviation - dataItem.LowerDeviation))
                        {
                            NG_FAI += dataItem.Name + @";";
                            dataItem.JugeResult = JUDGEMENT_RESULT.EXCEPTION.ToString();
                            if (ret != JUDGEMENT_RESULT.NA) ret = JUDGEMENT_RESULT.EXCEPTION;
                            continue;
                        }

                        if (dataItem.Value <= dataItem.NormValue + dataItem.UpperDeviation && dataItem.Value >= dataItem.NormValue + dataItem.LowerDeviation)
                        {
                            dataItem.JugeResult = JUDGEMENT_RESULT.OK.ToString();
                        }
                        else
                        {
                            NG_FAI += dataItem.Name + @";";
                            dataItem.JugeResult = JUDGEMENT_RESULT.NG.ToString();
                            if (ret != JUDGEMENT_RESULT.EXCEPTION && ret != JUDGEMENT_RESULT.NA)
                                ret = JUDGEMENT_RESULT.NG;
                        }
                    }
                    else
                    {
                        NG_FAI += dataItem.Name + @";";
                        dataItem.JugeResult = JUDGEMENT_RESULT.NA.ToString();
                        ret = JUDGEMENT_RESULT.NA;
                    }

                    if (Math.Abs(dataItem.Value - dataItem.NormValue) > 0.02)
                        IsBlockCheckRes = false;
                }
            }


            if (!IsExit && Common.isProductPointCheck && measureProduct.whichBlock == -1)
            {
                Common.GRRPointCheckTable.Rows.Add();
                Common.GRRPointCheckTable.Rows[Common.GRRPointCheckTable.Rows.Count - 1][0] = measureProduct.SN;
                foreach (var item in measureProduct.MeasureData)
                {
                    for (int i = 0; i < Common.GRRPointCheckTable.Columns.Count; i++)
                    {
                        if (item.Name == Common.GRRPointCheckTable.Columns[i].ColumnName)
                        {
                            Common.GRRPointCheckTable.Rows[Common.GRRPointCheckTable.Rows.Count - 1][item.Name] = item.Value;
                        }
                    }
                }
                FileUtils.SaveCSV(Common.GRRPointCheckTable, Common.pointCheckPath + @"\grr_standard_" + Common.CurProType + ".csv");
            }

            if (measureProduct.whichBlock == -1 && measureProduct.SN.Contains("NDK"))
            {
                ret = JUDGEMENT_RESULT.NA;
            }

            if (measureProduct.whichBlock != -1 && Common.IsNeedBlockCheck && !Common.屏蔽点检)
            {
                if (Common.Line == "右")
                {
                    if (measureProduct.Position == "1" || measureProduct.Position == "2")
                    {
                        if (!IsBlockCheckRes)
                        {
                            if (measureProduct.Position == "1") Common.BlockCheck1 = false;
                            if (measureProduct.Position == "2") Common.BlockCheck2 = false;
                            Common.AppendUiLog.Log($"{measureProduct.Position}号通道点检失败,请观察当前block物料", LogType.Error);
                            return JUDGEMENT_RESULT.NG;
                        }
                        else
                        {
                            if (measureProduct.Position == "1") Common.BlockCheck1 = true;
                            if (measureProduct.Position == "2") Common.BlockCheck2 = true;
                            Common.AppendUiLog.Log($"{measureProduct.Position}号通道点检成功！", LogType.Info);
                        }
                    }
                }
                else
                {
                    if (measureProduct.Position == "3" || measureProduct.Position == "4")
                    {
                        if (!IsBlockCheckRes)
                        {
                            if (measureProduct.Position == "3") Common.BlockCheck1 = false;
                            if (measureProduct.Position == "4") Common.BlockCheck2 = false;
                            Common.AppendUiLog.Log($"{measureProduct.Position}号通道点检失败,请观察当前block物料", LogType.Error);
                            return JUDGEMENT_RESULT.NG;
                        }
                        else
                        {
                            if (measureProduct.Position == "3") Common.BlockCheck1 = true;
                            if (measureProduct.Position == "4") Common.BlockCheck2 = true;
                            Common.AppendUiLog.Log($"{measureProduct.Position}号通道点检成功！", LogType.Info);
                        }
                    }
                }
            }


            measureProduct.NG_FAI = NG_FAI;
            return ret;
        }
    }
}
